package edu.zjucst.spb.cron;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import edu.zjucst.spb.dao.message.UserMessageDao;
import edu.zjucst.spb.dao.message.UserMessageTextDao;
import edu.zjucst.spb.domain.entity.message.UserMessage;
import edu.zjucst.spb.domain.entity.message.UserMessageText;
import edu.zjucst.spb.util.EmailManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * @author MrLi
 * @date 2023-05-26 20:16
 **/
@Component
@Slf4j
public class CronMessageNotifyJob {
    @Autowired
    private UserMessageTextDao userMessageTextDao;

    @Autowired
    private UserMessageDao userMessageDao;

    @Autowired
    private EmailManager emailManager;

    /**
     * 每天12点进行推送当天需要定时发送的消息
     */
    @Scheduled(cron = "0 0 12 * * ?")
    public void checkTodayNeedPushMessage() {
        LocalDate today = LocalDate.now();
        List<UserMessage> messages = userMessageDao.selectList(new LambdaQueryWrapper<UserMessage>()
            .eq(UserMessage::getNeedPush, true)
            .eq(UserMessage::getNeedPushTime, today)
        );
        for (UserMessage message : messages) {
            UserMessageText userMessageText = userMessageTextDao.selectById(message.getMessageId());
            emailManager.sendSimpleMail(message.getRecvUserId(), userMessageText.getTitle(), userMessageText.getContent());
            // 更新完成后设置
            message.setNeedPush(false);
            userMessageDao.update(message, new LambdaUpdateWrapper<UserMessage>().eq(UserMessage::getId, message.getId()));
        }
        log.info("每日消息推送执行完成, 本次共推送 {} 条消息", messages.size());
    }

    @Scheduled(cron = "0 0 11 * * ?")
    public void checkBeforeNeedPushMessage() {
        return;
    }
}
